<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <div style="font-size: 18px">注册设置</div>
      </div>
    </template>
    <div class="count">
      <p class="count-title">
        用户注册过程中，可动态配置是否采集考生基本信息（开启后为必填项）。
      </p>
      <el-checkbox-group v-model="selectedOptions">
        <el-checkbox label="isRegisterName">用户名</el-checkbox>
        <el-checkbox label="isRegisterLocation">院校信息</el-checkbox>
      </el-checkbox-group>
      <el-button type="primary" class="saveBtn" @click="saveBtn">
        保存
      </el-button>
    </div>
  </el-card>
</template>

<script setup>
import {
  registerSettingsApi,
  registerSettingsSave,
} from '@/api/system/registerSetting';
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

const selectedOptions = ref([]); // 存储选中的选项
const isRegisterName = ref(0);
const isRegisterLocation = ref(0);
const id = ref(1);

const getRegisterSetting = async () => {
  registerSettingsApi().then((res) => {
    if (res.code == 20000) {
      if (res.data == null) {
        id.value = 0;
      } else {
        // 解析返回的JSON数据
        const settingsData = JSON.parse(res.data.data);
        // 清空已选选项
        selectedOptions.value = [];
        // 遍历对象，将值为1的key添加到selectedOptions中
        for (const [key, value] of Object.entries(settingsData)) {
          if (value === 1) {
            selectedOptions.value.push(key);
          }
        }
      }
    }
  });
};

const saveBtn = () => {
  // 检查是否选中了用户名选项
  isRegisterName.value = selectedOptions.value.includes('isRegisterName')
    ? 1
    : 0;
  // 检查是否选中了所在地选项
  isRegisterLocation.value = selectedOptions.value.includes(
    'isRegisterLocation'
  )
    ? 1
    : 0;
  // 调用保存API，传递参数
  registerSettingsSave({
    id: id.value,
    data: JSON.stringify({
      isRegisterName: isRegisterName.value,
      isRegisterLocation: isRegisterLocation.value,
    }),
  }).then((res) => {
    if (res.code == 20000) {
      console.log('保存成功:', res);
      ElMessage.success('保存成功');
      id.value = 1;
    }
  });
};

onMounted(() => {
  getRegisterSetting();
});
</script>

<style lang="scss" scoped>
.count {
  display: flex;
  flex-direction: column;
  gap: 30px;
  .count-title {
    font-size: 14px;
    color: #909399;
  }
  .saveBtn {
    width: 150px;
  }
}
</style>
